<template>
  <view class="profile-container">
    <!-- 用户信息头部 -->
    <view class="profile-header">
      <view class="header-bg">
        <image :src="userInfo.backgroundImage" class="bg-image" mode="aspectFill"></image>
        <view class="header-overlay"></view>
      </view>
      
      <view class="user-info">
        <view class="avatar-section">
          <u-avatar 
            :src="userInfo.avatar" 
            size="80"
            class="user-avatar"
          ></u-avatar>
          <view class="user-badge" v-if="userInfo.isVip">
            <u-icon name="vip" color="#FFD700" size="16"></u-icon>
          </view>
        </view>
        
        <view class="user-details">
          <text class="username">{{ userInfo.username }}</text>
          <text class="user-desc" v-if="userInfo.description">{{ userInfo.description }}</text>
          <view class="user-tags" v-if="userInfo.tags && userInfo.tags.length > 0">
            <text 
              class="user-tag"
              v-for="tag in userInfo.tags" 
              :key="tag"
            >
              {{ tag }}
            </text>
          </view>
        </view>
        
        <!-- 关注按钮 -->
        <view class="follow-section" v-if="!isCurrentUser">
          <u-button 
            v-if="!userInfo.isFollowed"
            type="primary"
            size="small"
            :custom-style="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', border: 'none' }"
            @click="handleFollow"
          >
            + 关注
          </u-button>
          <u-button 
            v-else
            type="info"
            size="small"
            plain
            @click="handleUnfollow"
          >
            已关注
          </u-button>
        </view>
      </view>
      
      <!-- 统计数据 -->
      <view class="stats-section">
        <view class="stat-item" @click="handlePostsClick">
          <text class="stat-number">{{ userInfo.postCount || 0 }}</text>
          <text class="stat-label">帖子</text>
        </view>
        <view class="stat-item" @click="handleFollowingClick">
          <text class="stat-number">{{ userInfo.followingCount || 0 }}</text>
          <text class="stat-label">关注</text>
        </view>
        <view class="stat-item" @click="handleFollowersClick">
          <text class="stat-number">{{ userInfo.followersCount || 0 }}</text>
          <text class="stat-label">粉丝</text>
        </view>
        <view class="stat-item" @click="handleLikesClick">
          <text class="stat-number">{{ userInfo.totalLikes || 0 }}</text>
          <text class="stat-label">获赞</text>
        </view>
      </view>
    </view>

    <!-- 标签页导航 -->
    <view class="tab-navigation">
      <view 
        class="tab-item"
        :class="{ active: currentTab === 'posts' }"
        @click="switchTab('posts')"
      >
        <text class="tab-text">动态</text>
      </view>
      <view 
        class="tab-item"
        :class="{ active: currentTab === 'collections' }"
        @click="switchTab('collections')"
        v-if="isCurrentUser"
      >
        <text class="tab-text">收藏</text>
      </view>
      <view 
        class="tab-item"
        :class="{ active: currentTab === 'likes' }"
        @click="switchTab('likes')"
        v-if="isCurrentUser"
      >
        <text class="tab-text">点赞</text>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view 
      class="content-area" 
      scroll-y 
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 动态列表 -->
      <view class="posts-list" v-if="currentTab === 'posts'">
        <view 
          class="post-item modern-card"
          v-for="post in postList" 
          :key="post.id"
          @click="handlePostDetail(post)"
        >
          <!-- 帖子内容预览 -->
          <view class="post-preview">
            <text class="post-text">{{ post.content }}</text>
            <view class="post-images" v-if="post.mediaList && post.mediaList.length > 0">
              <image 
                :src="post.mediaList[0]" 
                class="preview-image"
                mode="aspectFill"
              ></image>
              <view class="image-count" v-if="post.mediaList.length > 1">
                <text class="count-text">{{ post.mediaList.length }}</text>
              </view>
            </view>
          </view>
          
          <!-- 帖子统计 -->
          <view class="post-stats">
            <text class="post-time">{{ formatTime(post.create_time) }}</text>
            <view class="stats-right">
              <view class="stat-item">
                <u-icon name="heart" color="#999" size="14"></u-icon>
                <text class="stat-text">{{ post.likeCount || 0 }}</text>
              </view>
              <view class="stat-item">
                <u-icon name="chat" color="#999" size="14"></u-icon>
                <text class="stat-text">{{ post.commentCount || 0 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 收藏列表 -->
      <view class="collections-list" v-if="currentTab === 'collections'">
        <view 
          class="collection-item modern-card"
          v-for="item in collectionList" 
          :key="item.id"
          @click="handlePostDetail(item)"
        >
          <view class="collection-content">
            <view class="content-left">
              <text class="collection-title">{{ item.title || item.content.substring(0, 30) + '...' }}</text>
              <text class="collection-desc">{{ item.content }}</text>
              <view class="collection-info">
                <text class="author-name">@{{ item.username }}</text>
                <text class="collect-time">{{ formatTime(item.collectTime) }}</text>
              </view>
            </view>
            <view class="content-right" v-if="item.mediaList && item.mediaList.length > 0">
              <image :src="item.mediaList[0]" class="collection-image" mode="aspectFill"></image>
            </view>
          </view>
        </view>
      </view>

      <!-- 点赞列表 -->
      <view class="likes-list" v-if="currentTab === 'likes'">
        <view 
          class="like-item modern-card"
          v-for="item in likeList" 
          :key="item.id"
          @click="handlePostDetail(item)"
        >
          <view class="like-content">
            <view class="content-left">
              <text class="like-title">{{ item.title || item.content.substring(0, 30) + '...' }}</text>
              <text class="like-desc">{{ item.content }}</text>
              <view class="like-info">
                <text class="author-name">@{{ item.username }}</text>
                <text class="like-time">{{ formatTime(item.likeTime) }}</text>
              </view>
            </view>
            <view class="content-right" v-if="item.mediaList && item.mediaList.length > 0">
              <image :src="item.mediaList[0]" class="like-image" mode="aspectFill"></image>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <u-loading-icon v-if="loading" color="#667eea" size="20"></u-loading-icon>
        <text class="load-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
      </view>
      
      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && getCurrentList().length === 0">
        <u-icon name="inbox" color="#ccc" size="60"></u-icon>
        <text class="empty-text">{{ getEmptyText() }}</text>
      </view>
    </scroll-view>

    <!-- 操作菜单 -->
    <view class="action-menu" v-if="isCurrentUser">
      <view class="menu-item" @click="handleEditProfile">
        <u-icon name="edit-pen" color="#667eea" size="20"></u-icon>
        <text class="menu-text">编辑资料</text>
      </view>
      <view class="menu-item" @click="handleSettings">
        <u-icon name="setting" color="#667eea" size="20"></u-icon>
        <text class="menu-text">设置</text>
      </view>
    </view>

  </view>
</template>

<script>
export default {
  data() {
    return {
      uid: '',
      isCurrentUser: false,
      currentTab: 'posts',
      refreshing: false,
      loading: false,
      hasMore: true,
      page: 1,
      pageSize: 10,
      
      // 用户信息
      userInfo: {},
      
      // 各种列表数据
      postList: [],
      collectionList: [],
      likeList: []
    }
  },
  
  onLoad(options) {
    this.uid = options.uid || uni.getStorageSync('currentUserId') || '1001'
    this.isCurrentUser = !options.uid || options.uid === uni.getStorageSync('currentUserId')
    this.initPage()
  },
  
  methods: {
    // 初始化页面
    async initPage() {
      await this.loadUserInfo()
      await this.loadCurrentTabData()
    },
    
    // 加载用户信息
    async loadUserInfo() {
      try {
        // 这里应该调用API获取用户信息
        // const res = await this.$api.getUserInfo(this.uid)
        
        // 模拟数据
        this.userInfo = {
          uid: this.uid,
          username: this.isCurrentUser ? '我' : '用户' + this.uid,
          avatar: 'https://cdn.uviewui.com/uview/album/1.jpg',
          backgroundImage: 'https://cdn.uviewui.com/uview/swiper/1.jpg',
          description: '热爱生活，喜欢摄影和旅行',
          tags: ['摄影爱好者', '旅行达人', '美食探索'],
          isVip: Math.random() > 0.5,
          isFollowed: !this.isCurrentUser && Math.random() > 0.5,
          postCount: Math.floor(Math.random() * 100) + 10,
          followingCount: Math.floor(Math.random() * 200) + 50,
          followersCount: Math.floor(Math.random() * 500) + 100,
          totalLikes: Math.floor(Math.random() * 1000) + 200
        }
      } catch (error) {
        console.error('加载用户信息失败:', error)
        this.showToast('加载用户信息失败', 'error')
      }
    },
    
    // 切换标签页
    switchTab(tab) {
      this.currentTab = tab
      this.page = 1
      this.loadCurrentTabData()
    },
    
    // 加载当前标签页数据
    async loadCurrentTabData() {
      switch (this.currentTab) {
        case 'posts':
          await this.loadPosts()
          break
        case 'collections':
          await this.loadCollections()
          break
        case 'likes':
          await this.loadLikes()
          break
      }
    },
    
    // 加载用户帖子
    async loadPosts() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        // 模拟数据
        const mockPosts = this.generateMockPosts()
        
        if (this.page === 1) {
          this.postList = mockPosts
        } else {
          this.postList.push(...mockPosts)
        }
        
        this.hasMore = mockPosts.length === this.pageSize
      } catch (error) {
        console.error('加载帖子失败:', error)
        this.showToast('加载失败，请重试', 'error')
      } finally {
        this.loading = false
      }
    },
    
    // 加载收藏列表
    async loadCollections() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        // 模拟数据
        const mockCollections = this.generateMockCollections()
        
        if (this.page === 1) {
          this.collectionList = mockCollections
        } else {
          this.collectionList.push(...mockCollections)
        }
        
        this.hasMore = mockCollections.length === this.pageSize
      } catch (error) {
        console.error('加载收藏失败:', error)
        this.showToast('加载失败，请重试', 'error')
      } finally {
        this.loading = false
      }
    },
    
    // 加载点赞列表
    async loadLikes() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        // 模拟数据
        const mockLikes = this.generateMockLikes()
        
        if (this.page === 1) {
          this.likeList = mockLikes
        } else {
          this.likeList.push(...mockLikes)
        }
        
        this.hasMore = mockLikes.length === this.pageSize
      } catch (error) {
        console.error('加载点赞失败:', error)
        this.showToast('加载失败，请重试', 'error')
      } finally {
        this.loading = false
      }
    },
    
    // 生成模拟帖子数据
    generateMockPosts() {
      const posts = []
      const contents = [
        '今天天气真好，出去拍了一些照片',
        '分享一下最近的读书心得',
        '推荐一个很棒的咖啡店',
        '周末和朋友们的聚会',
        '最近学习的新技能分享'
      ]
      
      for (let i = 0; i < this.pageSize; i++) {
        posts.push({
          id: Date.now() + i,
          content: contents[i % contents.length],
          mediaList: Math.random() > 0.5 ? [`https://cdn.uviewui.com/uview/album/${(i % 6) + 1}.jpg`] : [],
          create_time: new Date(Date.now() - Math.random() * 86400000 * 7).toISOString(),
          likeCount: Math.floor(Math.random() * 50),
          commentCount: Math.floor(Math.random() * 20)
        })
      }
      
      return posts
    },
    
    // 生成模拟收藏数据
    generateMockCollections() {
      const collections = []
      const contents = [
        '很有意思的摄影技巧分享',
        '这个地方的风景真的很美',
        '实用的生活小贴士',
        '值得收藏的美食制作方法',
        '有趣的旅行攻略'
      ]
      
      for (let i = 0; i < this.pageSize; i++) {
        collections.push({
          id: Date.now() + i,
          content: contents[i % contents.length],
          username: '用户' + (1000 + i),
          mediaList: Math.random() > 0.3 ? [`https://cdn.uviewui.com/uview/album/${(i % 6) + 1}.jpg`] : [],
          collectTime: new Date(Date.now() - Math.random() * 86400000 * 30).toISOString()
        })
      }
      
      return collections
    },
    
    // 生成模拟点赞数据
    generateMockLikes() {
      const likes = []
      const contents = [
        '点赞了这个精彩的分享',
        '很赞同这个观点',
        '这张照片拍得真好',
        '有用的信息，值得点赞',
        '支持这样的正能量内容'
      ]
      
      for (let i = 0; i < this.pageSize; i++) {
        likes.push({
          id: Date.now() + i,
          content: contents[i % contents.length],
          username: '用户' + (1000 + i),
          mediaList: Math.random() > 0.4 ? [`https://cdn.uviewui.com/uview/album/${(i % 6) + 1}.jpg`] : [],
          likeTime: new Date(Date.now() - Math.random() * 86400000 * 15).toISOString()
        })
      }
      
      return likes
    },
    
    // 获取当前列表
    getCurrentList() {
      switch (this.currentTab) {
        case 'posts':
          return this.postList
        case 'collections':
          return this.collectionList
        case 'likes':
          return this.likeList
        default:
          return []
      }
    },
    
    // 获取空状态文本
    getEmptyText() {
      switch (this.currentTab) {
        case 'posts':
          return this.isCurrentUser ? '还没有发布动态' : 'TA还没有发布动态'
        case 'collections':
          return '还没有收藏内容'
        case 'likes':
          return '还没有点赞内容'
        default:
          return '暂无内容'
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.refreshing = true
      this.page = 1
      await this.loadCurrentTabData()
      this.refreshing = false
    },
    
    // 加载更多
    async loadMore() {
      if (!this.hasMore) return
      
      this.page++
      await this.loadCurrentTabData()
    },
    
    // 格式化时间
    formatTime(timeStr) {
      const time = new Date(timeStr)
      const now = new Date()
      const diff = now - time
      
      if (diff < 60000) return '刚刚'
      if (diff < 3600000) return Math.floor(diff / 60000) + '分钟前'
      if (diff < 86400000) return Math.floor(diff / 3600000) + '小时前'
      if (diff < 604800000) return Math.floor(diff / 86400000) + '天前'
      
      return time.toLocaleDateString()
    },
    
    // 事件处理方法
    async handleFollow() {
      try {
        // 这里应该调用API关注用户
        this.userInfo.isFollowed = true
        this.userInfo.followersCount++
        this.showToast('关注成功', 'success')
      } catch (error) {
        this.showToast('关注失败，请重试', 'error')
      }
    },
    
    async handleUnfollow() {
      try {
        const res = await uni.showModal({
          title: '确认取消关注',
          content: `确定要取消关注"${this.userInfo.username}"吗？`
        })
        
        if (res.confirm) {
          // 这里应该调用API取消关注
          this.userInfo.isFollowed = false
          this.userInfo.followersCount--
          this.showToast('已取消关注', 'success')
        }
      } catch (error) {
        this.showToast('操作失败，请重试', 'error')
      }
    },
    
    handlePostsClick() {
      if (this.currentTab !== 'posts') {
        this.switchTab('posts')
      }
    },
    
    handleFollowingClick() {
      this.$tab.navigateTo(`/pages/user/following?uid=${this.uid}`)
    },
    
    handleFollowersClick() {
      this.$tab.navigateTo(`/pages/user/followers?uid=${this.uid}`)
    },
    
    handleLikesClick() {
      if (this.isCurrentUser && this.currentTab !== 'likes') {
        this.switchTab('likes')
      }
    },
    
    handlePostDetail(post) {
      this.$tab.navigateTo(`/pages/post/detail?id=${post.id}`)
    },
    
    handleEditProfile() {
      this.$tab.navigateTo('/pages/user/edit')
    },
    
    handleSettings() {
      this.$tab.navigateTo('/pages/user/settings')
    },
    
    showToast(title, type = 'default') {
      // 使用 uView 2.0 的 toast 方法
      this.$u.toast(title)
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-container {
  min-height: 100vh;
  background: #f8f9fa;
}

.profile-header {
  position: relative;
  background: white;
  margin-bottom: 10px;
  
  .header-bg {
    position: relative;
    height: 120px;
    
    .bg-image {
      width: 100%;
      height: 100%;
    }
    
    .header-overlay {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(135deg, rgba(102, 126, 234, 0.3) 0%, rgba(118, 75, 162, 0.3) 100%);
    }
  }
  
  .user-info {
    position: relative;
    padding: 0 20px 20px;
    margin-top: -40px;
    
    .avatar-section {
      position: relative;
      margin-bottom: 15px;
      
      .user-avatar {
        border: 4px solid white;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
      
      .user-badge {
        position: absolute;
        bottom: 5px;
        right: 5px;
        background: white;
        border-radius: 12px;
        padding: 2px;
      }
    }
    
    .user-details {
      margin-bottom: 15px;
      
      .username {
        font-size: 20px;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 8px;
      }
      
      .user-desc {
        font-size: 14px;
        color: #666;
        line-height: 1.4;
        margin-bottom: 10px;
        display: block;
      }
      
      .user-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        
        .user-tag {
          background: rgba(102, 126, 234, 0.1);
          color: #667eea;
          font-size: 12px;
          padding: 4px 8px;
          border-radius: 12px;
        }
      }
    }
    
    .follow-section {
      position: absolute;
      top: 15px;
      right: 20px;
    }
  }
  
  .stats-section {
    display: flex;
    justify-content: space-around;
    padding: 20px 0;
    border-top: 1px solid #f0f0f0;
    
    .stat-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .stat-number {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        margin-bottom: 4px;
      }
      
      .stat-label {
        font-size: 12px;
        color: #999;
      }
    }
  }
}

.tab-navigation {
  display: flex;
  background: white;
  margin-bottom: 10px;
  
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 15px 0;
    position: relative;
    
    &.active {
      .tab-text {
        color: #667eea;
        font-weight: 600;
      }
      
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 30px;
        height: 3px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        border-radius: 2px;
      }
    }
    
    .tab-text {
      font-size: 14px;
      color: #999;
    }
  }
}

.content-area {
  height: calc(100vh - 400px);
  padding: 0 15px;
}

.posts-list, .collections-list, .likes-list {
  .post-item, .collection-item, .like-item {
    margin-bottom: 15px;
    padding: 15px;
    
    .post-preview, .collection-content, .like-content {
      display: flex;
      justify-content: space-between;
      
      .content-left {
        flex: 1;
        margin-right: 15px;
        
        .post-text, .collection-title, .like-title {
          font-size: 14px;
          color: #333;
          line-height: 1.4;
          margin-bottom: 8px;
          display: block;
        }
        
        .collection-desc, .like-desc {
          font-size: 13px;
          color: #666;
          line-height: 1.4;
          margin-bottom: 8px;
          display: block;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
        
        .collection-info, .like-info {
          display: flex;
          gap: 10px;
          
          .author-name, .collect-time, .like-time {
            font-size: 12px;
            color: #999;
          }
          
          .author-name {
            color: #667eea;
          }
        }
      }
      
      .content-right {
        .preview-image, .collection-image, .like-image {
          width: 80px;
          height: 80px;
          border-radius: 8px;
        }
      }
    }
    
    .post-images {
      position: relative;
      
      .image-count {
        position: absolute;
        top: 5px;
        right: 5px;
        background: rgba(0, 0, 0, 0.6);
        color: white;
        font-size: 10px;
        padding: 2px 6px;
        border-radius: 10px;
        
        .count-text {
          color: white;
        }
      }
    }
    
    .post-stats {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-top: 12px;
      padding-top: 12px;
      border-top: 1px solid #f0f0f0;
      
      .post-time {
        font-size: 12px;
        color: #999;
      }
      
      .stats-right {
        display: flex;
        gap: 15px;
        
        .stat-item {
          display: flex;
          align-items: center;
          gap: 4px;
          
          .stat-text {
            font-size: 12px;
            color: #999;
          }
        }
      }
    }
  }
}

.load-more {
  text-align: center;
  padding: 20px;
  
  .load-text {
    font-size: 14px;
    color: #999;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  
  .empty-text {
    font-size: 16px;
    color: #999;
    margin-top: 20px;
    display: block;
  }
}

.action-menu {
  position: fixed;
  bottom: 20px;
  right: 20px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  
  .menu-item {
    background: white;
    border-radius: 25px;
    padding: 12px 16px;
    display: flex;
    align-items: center;
    gap: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    
    .menu-text {
      font-size: 14px;
      color: #333;
    }
  }
}
</style>